# Go相关配置
GO          := go
GOBUILD     := $(GO) build
GOTEST      := $(GO) test
GOINSTALL   := $(GO) install
GOFMT       := $(GO) fmt
GOMOD       := $(GO) mod

# 项目相关配置
PROJECT     := $(basename $(notdir $(MAKEFILE_LIST)))
BINARY_NAME := $(PROJECT)SteedCensorShield
MAIN_FILE   := cmd/main.go
VERSION     := $(shell git describe --tags --always | tr -d '[:space:]')
OUTPUT_DIR  := ./bin

# 支持的平台
PLATFORMS := linux/amd64 linux/386 linux/arm linux/arm64 linux/ppc64 linux/ppc64le linux/mips linux/mipsle linux/mips64 linux/mips64le darwin/amd64 darwin/arm64 windows/amd64 windows/386 freebsd/amd64 freebsd/386 freebsd/arm freebsd/arm64

# Makefile中的伪目标
.PHONY: build clean all test install fmt help $(PLATFORMS)

# 构建目标
all: clean $(PLATFORMS)

# 使用循环结构来动态生成构建规则
define BUILD_template
build-$(1):
	@echo "Building for platform $(1)"
	$(eval OS := $(word 1, $(subst /, ,$(1))))
	$(eval ARCH := $(word 2, $(subst /, ,$(1))))
	@$(GOBUILD) -o "$(OUTPUT_DIR)/$(OS)-$(ARCH)/$(BINARY_NAME)-$(VERSION)$(if $(findstring windows,$(OS)),.exe,)" $(MAIN_FILE)
endef

# 应用循环结构
$(foreach platform,$(PLATFORMS),$(eval $(call BUILD_template,$(platform))))

# 定义每个平台的构建规则
$(PLATFORMS): 
	$(eval OS := $(word 1, $(subst /, ,$@)))
	$(eval ARCH := $(word 2, $(subst /, ,$@)))
	@$(MAKE) build-$@

# 运行测试
test:
	@echo "Running tests..."
	@$(GOTEST) ./...

# 安装项目，可选
install:
	@echo "Installing $(BINARY_NAME)..."
	@$(GOINSTALL) $(MAIN_FILE)

# 清理生成的文件
clean:
	@echo "Cleaning..."
	@rm -rf $(OUTPUT_DIR)

# 格式化代码
fmt:
	@echo "Formatting code..."
	@$(GOFMT) ./...


deps:
	@echo "Fetching dependencies..."
	@$(GOMOD) tidy

# 显示帮助信息
help:
	@echo "Usage: make [target]"
	@echo ""
	@echo "Targets:"
	@echo "  build    Build the project for all supported platforms"
	@echo "  test     Run tests"
	@echo "  install  Install the project"
	@echo "  clean    Clean the build artifacts"
	@echo "  fmt      Format the source code"
	@echo "  help     Show this help message"

# 默认目标
.DEFAULT_GOAL := all
